package com.dcivision.framework.taglib.channel;

import java.sql.Connection;
import java.sql.Timestamp;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.PageContext;

import com.dcivision.alert.AlertOperationConstant;
import com.dcivision.alert.bean.UpdateAlert;
import com.dcivision.alert.bean.UpdateAlertSystemLog;
import com.dcivision.alert.core.MessageFormatter;
import com.dcivision.alert.core.MessageFormatterFactory;
import com.dcivision.dms.bean.DmsDocument;
import com.dcivision.dms.core.DocumentRetrievalManager;
import com.dcivision.framework.ApplicationException;
import com.dcivision.framework.GlobalConstant;
import com.dcivision.framework.PermissionManager;
import com.dcivision.framework.SessionContainer;
import com.dcivision.framework.Utility;

public abstract class AjaxStandardMessageFormatter extends AbstractAjaxChannelFormatter {
  // --should init---
  protected AjaxTagFactory ajaxFactory = null;

  // ----------for {}
  MessageFormatter messageFormatter = null;

  UpdateAlertSystemLog updateAlertSystemLog = null;

  public AjaxStandardMessageFormatter() {
    // empty
  }

  public AjaxStandardMessageFormatter(PageContext pageContext, int pageSize, List channelList) {
    this.pageContext = pageContext;
    this.channelList = channelList;
    this.pageSize = pageSize;
    init();
  }

  public void init() {
    super.init();
    ajaxFactory = (AjaxTagFactory) pageContext.getRequest().getAttribute(AjaxConstant.AJAXTAGFACTORY);
    this.columnCount = 4;
    this.pattern = "common.channel.message_inbox";
  }

  public String[] getContent() throws Exception {
    StringBuffer bstr = new StringBuffer();
    int i = 0;
    for (Iterator it = channelList.iterator(); it.hasNext();) {
      i++;
      updateAlertSystemLog = (UpdateAlertSystemLog) it.next();
      Connection dbConn = (Connection) ((HttpServletRequest) pageContext.getRequest()).getAttribute(GlobalConstant.DB_KEY);
      messageFormatter = MessageFormatterFactory.getInstance().getMessageFormatter(updateAlertSystemLog,
          (SessionContainer) pageContext.getSession().getAttribute(GlobalConstant.SESSION_CONTAINER_KEY), dbConn);
      bstr.append("<tr>");
      if (i < pageSize && i < channelList.size()) {
        bstr.append(getRead());
        bstr.append(getSender());
        bstr.append(getSubject());
        bstr.append(getReceivedDate());
      } else {
        bstr.append(addStyle(getRead()));
        bstr.append(addStyle(getSender()));
        bstr.append(addStyle(getSubject()));
        bstr.append(addStyle(getReceivedDate()));
      }
      bstr.append("</tr>");
    }
    // bstr.append(this.getPageInfoContent(columnCount));
    // return bstr.toString();
    return this.parsePageInfo(bstr);
  }

  /**
   * @return string
   */
  private String addStyle(String oldStr) {
    return oldStr.replaceFirst("<td", "<td style=\" border-bottom:none \" ");
  }

  protected abstract String getRead() throws ApplicationException;

  protected abstract String getSender() throws ApplicationException;

  protected abstract String getSubject() throws ApplicationException;

  protected abstract String getReceivedDate() throws ApplicationException;

  private String getEventExecuteFunction() {
    String scriptFunction = "eventExecute('" + AjaxConstant.MESSAGEINBOXFILTER + "','" + AjaxConstant.MESSAGEINBOXFILTER
        + "','updateReadOperationLog',new Array('" + updateAlertSystemLog.getID() + "','" + AlertOperationConstant.READ_OPERATION
        + "'),30,this)";
    return scriptFunction;
  }

  protected String getRead(StringBuffer bstr) throws ApplicationException {
    bstr.append("<input type=\"checkbox\" name= \"basicSelectedID\" value=\"" + updateAlertSystemLog.getID() + "\" onclick=\"checkButtonClass(\'markButton\',\'basicSelectedID\')\"");
    return bstr.toString();
  }

  protected String getSender(StringBuffer bstr) throws ApplicationException {
    bstr.append(messageFormatter.getSender());
    return bstr.toString();
  }

  protected Integer getDocumentObjectID(UpdateAlertSystemLog systemLog) {
    Integer objectID = null;
    String objectType = systemLog.getObjectType().trim();
    
    boolean isDms = (UpdateAlert.DOCUMENT_TYPE.equals(objectType))
    || (UpdateAlert.AUTOMATE_CHECKIN.equals(objectType))
    || (UpdateAlert.ISSUE_TYPE.equals(objectType));
    
    if (isDms) {
      if(Utility.isEmpty(systemLog.getRefObjectID())
          ||UpdateAlert.DOCUMENT_INVITATION_CANCEL.equals(systemLog.getActionType())
          ||UpdateAlert.DOCUMENT_INVITATION_EXPIRED.equals(systemLog.getActionType())
          ||UpdateAlert.DOCUMENT_INVITATION_UPDATE_DUEDATE.equals(systemLog.getActionType())){
        objectID = systemLog.getObjectID();
          }else{
            objectID = systemLog.getRefObjectID();
          }
    }
    return objectID;
  }

  protected String getSubject(StringBuffer bstr) throws ApplicationException {
    if (!Utility.isEmpty(getDocumentObjectID(updateAlertSystemLog))) {
      DocumentRetrievalManager docRetrievalManager = new DocumentRetrievalManager(sessionContainer, conn);
      DmsDocument dmsDocument = docRetrievalManager.getDocument(getDocumentObjectID(updateAlertSystemLog));
      String docName = dmsDocument.getDocumentName();
      String subject = messageFormatter.getSubject();
      if (subject.lastIndexOf(docName) >= 0) {
        PermissionManager permissionManager = sessionContainer.getPermissionManager();
        String permission = permissionManager.getPermission(conn, GlobalConstant.OBJECT_TYPE_DOCUMENT,
            getDocumentObjectID(updateAlertSystemLog));
        AjaxDMSContextMenuTag tag = (AjaxDMSContextMenuTag) ajaxFactory.getAjaxTag(pageContext, AjaxConstant.DMSCONTEXTMENUTAG);
        tag.setDmsDocument(dmsDocument);
        AjaxDocumentInfoTag documentInfo = (AjaxDocumentInfoTag) ajaxFactory.getAjaxTag(pageContext, AjaxConstant.documentInfoTag);
        documentInfo.setDocObject(dmsDocument);
        documentInfo.setPermission(permission);

        int docIndex = subject.lastIndexOf(docName);
        String subjectLeft = subject.substring(0, docIndex);
        if (subjectLeft.lastIndexOf(":") >= 0) {
          subjectLeft = subjectLeft.substring(0, subjectLeft.lastIndexOf(":"));
        }
        subjectLeft = " <strong> " + subjectLeft + "</strong>";
        subjectLeft = subjectLeft + ":[";
        String subjectMiddle = subject.substring(docIndex + docName.length());
        bstr.append(subjectLeft + tag.getAjaxContext() + "<nobr>" + documentInfo.getAjaxContent() + "</nobr>");
        DmsDocument folderDocument = docRetrievalManager.getDocument(dmsDocument.getParentID());
        String folderName = folderDocument.getDocumentName();
        if (subjectMiddle.indexOf(folderName) >= 0) {
          String folderPermission = permissionManager.getPermission(conn, GlobalConstant.OBJECT_TYPE_DOCUMENT, dmsDocument.getParentID());
          AjaxDocumentInfoTag folderDocumentInfo = new AjaxDocumentInfoTag();
          folderDocumentInfo.release();
          folderDocumentInfo.setPageContext(pageContext);
          folderDocumentInfo.setDocObject(folderDocument);
          folderDocumentInfo.setPermission(folderPermission);

          int folderIndex = subjectMiddle.indexOf(folderName);
          String subjectRight = subjectMiddle.substring(folderIndex + folderName.length());
          subjectMiddle = subjectMiddle.substring(0, folderIndex);
          bstr.append(subjectMiddle + "<nobr>" + folderDocumentInfo.getAjaxContent() + "</nobr>" + subjectRight);
        } else {
          bstr.append(subjectMiddle);
        }
      }
    } else {
      bstr.append("<strong>" + messageFormatter.getSubject() + "</strong>");
    }
    return bstr.toString();
  }

  protected String getReceivedDate(StringBuffer bstr) throws ApplicationException {
    // bstr.append(new AjaxDataFormat(updateAlertSystemLog.getCreateDate(),new
    // Timestamp(System.currentTimeMillis()),"ago").format());
    AjaxDurationTag tag = (AjaxDurationTag) ajaxFactory.getAjaxTag(pageContext, AjaxConstant.durationTag);
    tag.setStartDate(updateAlertSystemLog.getCreateDate().toString());
    tag.setEndDate(new Timestamp(System.currentTimeMillis()).toString());
    bstr.append(tag.getAjaxContent());
    ajaxFactory.releaseTag(AjaxConstant.durationTag, tag);
    return bstr.toString();
  }
}
